package com.example.abc.config;

import com.example.abc.service.DatabaseUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * Created by Peter on 2018/4/24.
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DatabaseUserDetailService userDetailsService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin().and()// 允许同源网站使用iframe
                .authorizeRequests()
                .antMatchers("/static/**", "/index", "/error", "/register", "/favicon.ico").permitAll()// 匹配允许访问
                .anyRequest().authenticated()
//                .and().csrf().disable() // 启用了csrf后所有的 PATCH, POST, PUT, 和 DELETE 请求必须包含“_csrf”参数
                .and().formLogin().loginPage("/login").permitAll()
                .and().logout().logoutUrl("/logout").permitAll()
                .and().exceptionHandling().defaultAuthenticationEntryPointFor(getAuthenticationEntryPoint(), new AntPathRequestMatcher("/logined"))
                .and()
                .sessionManagement()
                .maximumSessions(100)                //(1)To register SessionRegistry bean, we need ConcurrencyControlConfigurer which is only provided by http.sessionManagement().maximumSessions(int) call. That’s why I specified it to be a large number, because I don’t want to limit users.
                .maxSessionsPreventsLogin(false)    //(2) I had to limit maximum session count but I don’t want to prevent a user from logging in.
                .expiredUrl("/login")               //(3)
                .sessionRegistry(sessionRegistry())  //(4)
        ;
        ;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    // 特殊处理ajax请求，用户未登录时返回http code 为440
    @Bean
    AuthenticationEntryPoint getAuthenticationEntryPoint() {
        return new AjaxAwareAuthEntryPointWrapper("/login");
    }

    @Bean
    SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    //To tell Spring to store sessions in the registry, we need HttpSessionEventPublisher bean.
    @Bean
    public static ServletListenerRegistrationBean httpSessionEventPublisher() {    //(5)
        return new ServletListenerRegistrationBean(new HttpSessionEventPublisher());
    }

    @Bean
    PermissionEvaluator getPermissionEvaluator() {
        return new MyPermissionEvaluator();
    }
}
